package com.archstoday.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.archstoday.BaseApp;
import com.archstoday.R;
import com.archstoday.common.AsRes;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.BaseEntity;
import com.archstoday.entity.ShareEntity;
import com.archstoday.entity.TenderDetailsEntity;
import com.archstoday.utils.OAuthUtils;
import com.archstoday.utils.ToolUtils;
import com.archstoday.utils.WechatUtils;
import com.base.http.common.BaseHttpClient;
import com.base.utils.MySharedPreferencesMgr;
import com.base.utils.StringUtil;
import com.shuyu.action.web.ActionSelectListener;
import com.shuyu.action.web.CustomActionWebView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 招投标/工程实务详情
 */
public class TenderDetailsActivity extends AsBaseActivity {

    private TextView mTitleTv;
    private LinearLayout mHeadLayout, mStartTimeLayout,
            mEndTimeLayout, mOpenTimeLayout, mPurchaseLayout;
    private TextView mDetailsTitleTv, mStartTimeTv, mEndTimeTv,
            mOpenTimeTv, mPurchaseTv, mAgentTv, mLikeBtn, mReadBtn;
    private CustomActionWebView mWebView;

    private TenderDetailsEntity mEntity;
    private String mChannel;
    private String articleId;
    private String mAction;

    List<String> list;

    private MyTimeTask mTimeTask;
    private Timer timer;
    private int recLen;

    class MyTimeTask extends TimerTask {
        @Override
        public void run() {
            Message message = new Message();
            handler.sendMessage(message);
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            if(recLen == 0){
                mLikeBtn.setEnabled(true);
            }
            recLen--;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimeTask != null) {
            mTimeTask.cancel();
        }
    }

    @Override
    protected void initView(Bundle bundle) {
        setContentView(R.layout.activity_tender_details);
        mTitleTv = (TextView) findViewById(R.id.title_tv);
        mHeadLayout = (LinearLayout) findViewById(R.id.details_head_layout);
        mStartTimeLayout = (LinearLayout) findViewById(R.id.details_start_time_layout);
        mEndTimeLayout = (LinearLayout) findViewById(R.id.details_end_time_layout);
        mOpenTimeLayout = (LinearLayout) findViewById(R.id.details_open_time_layout);
        mPurchaseLayout = (LinearLayout) findViewById(R.id.details_purchase_name_layout);
        mDetailsTitleTv = (TextView) findViewById(R.id.details_title_tv);
        mStartTimeTv = (TextView) findViewById(R.id.details_start_time_tv);
        mEndTimeTv = (TextView) findViewById(R.id.details_end_time_tv);
        mOpenTimeTv = (TextView) findViewById(R.id.details_open_time_tv);
        mPurchaseTv = (TextView) findViewById(R.id.details_purchase_name_tv);
        mAgentTv = (TextView) findViewById(R.id.details_agent_name_tv);
        mLikeBtn = (TextView) findViewById(R.id.details_like_btn);
        mReadBtn = (TextView) findViewById(R.id.details_btn);
        mWebView = (CustomActionWebView) findViewById(R.id.details_content_view);
    }

    @Override
    protected void initData(Bundle bundle) {
        mTitleTv.setText(StringUtil.isEmpty(getIntent().getStringExtra("title"))
                ? "招标公告" : getIntent().getStringExtra("title"));
        articleId = getIntent().getStringExtra("id");

        list = new ArrayList<>();
        list.add("拷贝");
        list.add("分享文字");

        initSetting();
        upData();
    }

    private void initSetting() {
        WebSettings ws = mWebView.getSettings();
        ws.setBuiltInZoomControls(false);
        ws.setSupportZoom(false);
        ws.setJavaScriptEnabled(true);
        ws.setAllowFileAccess(true);
        ws.setSupportMultipleWindows(true);
        ws.setJavaScriptCanOpenWindowsAutomatically(true);
        ws.setLoadsImagesAutomatically(true);
        ws.setDomStorageEnabled(true);
        ws.setDisplayZoomControls(false);
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        ws.setUseWideViewPort(true);
        ws.setLoadWithOverviewMode(true);
        mWebView.setWebChromeClient(new WebChromeClient());

        mWebView.setWebViewClient(new CustomWebViewClient());

        //设置item
        mWebView.setActionList(list);

        //链接js注入接口，使能选中返回数据
        mWebView.linkJSInterface();

        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setDisplayZoomControls(false);
        //使用javascript
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);

        //增加点击回调
        mWebView.setActionSelectListener(new ActionSelectListener() {

            @Override
            public void onClick(String title, String selectText) {
                Log.e("onClick", "onClick--");

                if (title.equalsIgnoreCase("分享文字")) {
                    Intent intent = new Intent();
                    intent.putExtra("id", Integer.parseInt(articleId));
                    intent.putExtra("content", selectText);
                    intent.putExtra("type", "recruit");
                    intent.putExtra("categoryId1", mEntity.getData().getCategoryId1());

                    intent.setClass(mContext, TextShareActivity.class);
                    startActivity(intent);
                }

                if (title.equalsIgnoreCase("拷贝")) {
                    ToolUtils.copyUrl(mContext, selectText);
                }
            }
        });
    }

    @Override
    protected void initListener() {
        setOnClickListener(R.id.back_btn);
        setOnClickListener(R.id.details_btn);
        setOnClickListener(R.id.details_like_btn);
        setOnClickListener(R.id.details_share_btn);
    }

    @Override
    public void treatClickEvent(int id) {
        switch (id) {
            case R.id.back_btn:
                appFinish();
                break;
            case R.id.details_btn:
                getEvent(mApp.E_READ, mApp.PAGE_TYPE_READ);
                Intent intent = new Intent(mContext, WebActivity.class);
                intent.putExtra("url", mEntity.getData().getSourceDetailLink());
                startActivity(intent);
                break;
            case R.id.details_like_btn:
                if (StringUtil.isEmpty(MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""))) {
                    showToast(R.string.user_userid_null);

                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivity(loginIntent);
                    appFinish();
                } else {
                    if (mLikeBtn.isSelected()) {
                        mAction = "del";
                        like();
                    } else {
                        mAction = "add";
                        like();
                    }

                    mLikeBtn.setEnabled(false);
                    timer = new Timer();
                    mTimeTask = new MyTimeTask();
                    recLen = 1;
                    timer.schedule(mTimeTask, 1000, 1000);
                }
                break;
            case R.id.details_share_btn:
                setDialog();
                break;
            case R.id.share_wx_btn:
                Map<String, String> info = new HashMap<>();
                info.put("articleId", String.valueOf(mEntity.getData().getArticleId()));
                info.put("categoryId1", String.valueOf(mEntity.getData().getCategoryId1()));
                info.put("channel", "wechat");
                getEvent(BaseApp.E_DETAILS_SHARE, BaseApp.PAGE_TYPE_DETAILS_SHARE,
                        ToolUtils.mapToJson(info));

                mChannel = "wechat";
                share();
                break;
            case R.id.share_group_btn:
                info = new HashMap<>();
                info.put("articleId", String.valueOf(mEntity.getData().getArticleId()));
                info.put("categoryId1", String.valueOf(mEntity.getData().getCategoryId1()));
                info.put("channel", "friends");
                getEvent(BaseApp.E_DETAILS_SHARE, BaseApp.PAGE_TYPE_DETAILS_SHARE,
                        ToolUtils.mapToJson(info));


                mChannel = "friends";
                share();
                break;
            case R.id.share_link_btn:
                info = new HashMap<>();
                info.put("articleId", String.valueOf(mEntity.getData().getArticleId()));
                info.put("categoryId1", String.valueOf(mEntity.getData().getCategoryId1()));
                info.put("channel", "link");
                getEvent(BaseApp.E_DETAILS_SHARE, BaseApp.PAGE_TYPE_DETAILS_SHARE,
                        ToolUtils.mapToJson(info));


                mChannel = "msg";
                share();
                break;
        }
    }

    private void like() {
        initParameter();
        mParams.put("articleId", getIntent().getStringExtra("id"));
        mParams.put("categoryId1", mEntity.getData().getCategoryId1());
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("plat", "android");
        mParams.put("ifa", mApp.getDeviceID(mContext));
        mParams.put("action", mAction);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.EDIT_LIKE),
                AsRes.EDIT_LIKE, mParams, BaseEntity.class);
    }

    private void upData() {
        initParameter();
        mParams.put("id", Integer.valueOf(articleId));
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("toke", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_RECRUIT_DETAILS),
                AsRes.GET_RECRUIT_DETAILS, mParams, TenderDetailsEntity.class);
    }

    private void share() {
        initParameter();
        mParams.put("articleID", Integer.valueOf(articleId));
        mParams.put("type", "recruit");
        mParams.put("channel", mChannel);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.SHARE),
                AsRes.SHARE, mParams, ShareEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        if (client.getUrlIdentifier() == AsRes.GET_RECRUIT_DETAILS) {
            mEntity = (TenderDetailsEntity) parse;
            if (ToolUtils.isSuccess(mEntity.getStatus())) {
                mDetailsTitleTv.setText(mEntity.getData().getTitle());
                if (StringUtil.isEmpty(mEntity.getData().getStartTime())
                        && StringUtil.isEmpty(mEntity.getData().getDeadlineTime())
                        && StringUtil.isEmpty(mEntity.getData().getBidOpenTime())
                        && StringUtil.isEmpty(mEntity.getData().getRecruitOrg())) {
                    mHeadLayout.setVisibility(View.GONE);
                } else {
                    mHeadLayout.setVisibility(View.VISIBLE);
                    if (StringUtil.isEmpty(mEntity.getData().getStartTime())) {
                        mStartTimeLayout.setVisibility(View.GONE);
                    } else {
                        mStartTimeTv.setText(mEntity.getData().getStartTime());
                    }
                    if (StringUtil.isEmpty(mEntity.getData().getDeadlineTime())) {
                        mEndTimeLayout.setVisibility(View.GONE);
                    } else {
                        mEndTimeTv.setText(mEntity.getData().getDeadlineTime());
                    }
                    if (StringUtil.isEmpty(mEntity.getData().getBidOpenTime())) {
                        mOpenTimeLayout.setVisibility(View.GONE);
                    } else {
                        mEndTimeTv.setText(mEntity.getData().getDeadlineTime());
                    }
                    if (StringUtil.isEmpty(mEntity.getData().getRecruitOrg())) {
                        mPurchaseLayout.setVisibility(View.GONE);
                    } else {
                        mOpenTimeTv.setText(mEntity.getData().getBidOpenTime());
                    }
                }
                mPurchaseTv.setText(mEntity.getData().getRecruitOrg());
                mAgentTv.setText(mEntity.getData().getAgentName());
                mLikeBtn.setText(String.valueOf(mEntity.getData().getUpvote()));
                mLikeBtn.setSelected(mEntity.getData().getIslike() == 1 ? true : false);
//                if (mEntity.getData().getIslike() == 0) {
//                    mLikeBtn.setTextColor(mContext.getResources().getColor(R.color.black));
//                } else {
//                    mLikeBtn.setTextColor(mContext.getResources().getColor(R.color.scheme_yellow));
//                }

                mReadBtn.setVisibility(StringUtil.isEmpty(mEntity.getData().getSourceDetailLink())
                        ? View.GONE : View.VISIBLE);

                mWebView.loadDataWithBaseURL(null,
                        mEntity.getData().getContent(), "text/html", "utf-8", null);
            } else {
                showToast(mEntity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.SHARE) {
            ShareEntity entity = (ShareEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                getEvent(mApp.E_SHARE, mApp.PAGE_TYPE_SHARE);
                switch (mChannel) {
                    case "wechat":
                        WechatUtils.share(mContext, entity.getData().getTitel(),
                                entity.getData().getDesp(), entity.getData().getUrl(),
                                false);
                        break;
                    case "friends":
                        WechatUtils.share(mContext, entity.getData().getTitel(),
                                entity.getData().getDesp(), entity.getData().getUrl(),
                                true);
                        break;
                    case "msg":
                        ToolUtils.copyUrl(mContext, entity.getData().getUrl());
                        break;
                }
                dismissShare();
            } else {
                showToast(entity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.EDIT_LIKE) {
            BaseEntity entity = (BaseEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                switch (mAction) {
                    case "add":
                        mLikeBtn.setText(String.valueOf(mEntity.getData().getUpvote() + 1));
                        mEntity.getData().setUpvote(mEntity.getData().getUpvote() + 1);
                        break;
                    case "del":
                        mLikeBtn.setText(String.valueOf(mEntity.getData().getUpvote() - 1));
                        mEntity.getData().setUpvote(mEntity.getData().getUpvote() - 1);
                        break;
                }
                mLikeBtn.setSelected(!mLikeBtn.isSelected());
            } else if (entity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            } else {
                showToast(entity.getMsg());
            }
        }
    }

    private class CustomWebViewClient extends WebViewClient {

        private boolean mLastLoadFailed = false;

        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            if (!mLastLoadFailed) {
                CustomActionWebView customActionWebView = (CustomActionWebView) webView;
                customActionWebView.linkJSInterface();
            }
        }

        @Override
        public void onPageStarted(WebView webView, String url, Bitmap favicon) {
            super.onPageStarted(webView, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mLastLoadFailed = true;
        }
    }
}